package uk.co.pc.domain.dao.impl;

import java.util.List;

import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import uk.co.pc.domain.dao.ArticleDao;
import uk.co.pc.domain.model.Article;

/**
 * ArticleDao.
 * 
 * This class must implement persistence logic for the Article.
 * 
 * Assume happy path with no exceptions.
 */
@Repository
@Transactional(readOnly = true)
public class ArticleDaoImpl extends HibernateDaoSupport implements ArticleDao {

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Article save(Article article) {
		getSession().saveOrUpdate(article);
		return article;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void delete(Long id) {
		getSession().delete(findById(id));
	}

	@Override
	public Article findById(Long id) {
		Object article = getSession().get(Article.class, id);
		if (article != null) {
			return (Article) article;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Article> findByTitle(String title) {
		return getSession().createCriteria(Article.class)
		.add(Restrictions.ilike("title", title, MatchMode.ANYWHERE))
		.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Article> findByAuthor(String author) {
		return getSession().createCriteria(Article.class)
		.add(Restrictions.ilike("author", author, MatchMode.ANYWHERE))
		.list();
	}
   

}
